<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
		
if (!isset($_POST['is_submitted'])) {
	$_POST['is_submitted'] = '';
}
if (!isset($error_message)) {
	$error_message = '';
}	



$id = $_REQUEST["catalog_id"];
if($id)  $_SESSION["catalog_id"] = $id;
if(!$id) $id = $_SESSION["catalog_id"];
$cat_id = $id;

$redirect = $_SERVER['HTTP_REFERER'];	


	$dr = "../catalogimage/".$id."/";
if ($_FILES['image']['name'] &&  $_POST["is_uploud"])
		{
			$sql = "INSERT INTO catalog_image
					  (catalog_id)
					VALUES
					  ('$id')
					  ";
			query($sql);
			$image_id = mysql_insert_id();
			
			
			define('IMAGE_WIDTH',CAT_IMAGE_WIDTH);
			define('IMAGE_HEIGHT', CAT_IMAGE_HEIGHT);
			define('THUMB_WIDTH',CAT_THUMB_WIDTH);
			define('THUMB_HEIGHT',CAT_THUMB_HEIGHT);
			
			
			if(!is_dir($dr)) mkdir($dr, 0755); 
			include '../../include/image_man.php';
			$imn = new ImageManipulator;
		
		
		if (is_uploaded_file($_FILES['image']['tmp_name'])) {
				
			$tmp_file = $_FILES['image']['tmp_name'];
			$exp = explode('.',$_FILES['image']['name']);
			$img_type = strtolower(end($exp));
			$imn -> decider($img_type,$tmp_file);
			
			
			///////////////////////////////////////////////
			
			
			if(copy($tmp_file.'_image', $dr.'image_'.$image_id.'.'.$img_type) && copy($tmp_file.'_thumb', $dr.'th_image_'.$image_id.'.'.$img_type))
			{
				$sql = 'UPDATE catalog_image
						SET
							image = \'image_'.$image_id.'.'.$img_type.'\'
						WHERE
							image_id = '.$image_id.'
						  ';
				query($sql);
				redirect('catalog_edit.php?catalog_id='.$id);
			} else {
				$sql = 'DELETE FROM 
						   catalog_image
						WHERE
						   image_id = '.$image_id.'
						 ';
				query($sql);
				$error_message .= 'Error при качване на снимка. ';
				
			}	
			
		}
			
			
		}else{
			if($_POST["is_uploud"]) $error_message .= 'Не е избрана снимка<br/>';
		}


	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	$sql = 'SELECT lang_id,Name,code FROM language WHERE published';
	$result_lang = query($sql);
	
	while ($row_lang = mysql_fetch_object($result_lang)) {
				$em = $row_lang->lang_id;
				eval('$title =  $_POST[\'title_'.$em.'\'];');
				if (!$title)  $error_message .= 'Не е въведено заглавие на '.$row_lang->title.'<br/>';
				
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
				if (!$meta_d)  $error_message .= 'Не е въведено мета описание на '.$row_lang->Name.'<br/>';
	}
	/*if (!$_POST['category_id'])  $error_message .= 'Не е избрана категория!<br/>';*/
	
	
	
	
	
	if (!$_POST['seo_url'])  $error_message .= 'Не е въведено SEF URL<br/>';
		elseif(!preg_match('/^[0-9A-Za-z\-\_]+$/', $_POST['seo_url'])) $error_message .= 'Въведеният SEF URL е невалиден<br/>';
		
	$sql = "SELECT
				catalog_id
			FROM
				catalog
			WHERE
				sef_url = '".$_POST['seo_url']."'
				AND 
				catalog_id != '$cat_id'
			  ";
	$result = query($sql);
	if ($row_seo = mysql_fetch_object($result)) $error_message .= 'Въведеният SEF URL вече е използван<br/>';
	
	
	
	//ОК
    if(!$error_message) {
		
		$upload_path = "../catalogimage/";
		
		$sql = 'SELECT MAX(order_number)+1 AS order_number FROM catalog';
		$row_number = mysql_fetch_assoc(query($sql));
		
		//Създаваме проекта
		$sql = "UPDATE catalog SET
				  sef_url = '".escape($_POST['seo_url'])."'
				  
				 WHERE
				 catalog_id = '$cat_id'
				";
		query($sql);
		
		$sql = 'SELECT lang_id,Name,code
				FROM
				language
				WHERE
				published
					';
		$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			$em = $row_lang->lang_id;
				eval('$title =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$meta_k =  $_POST[\'meta_key_'.$em.'\'];');
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
			
			$sql = "UPDATE catalog_description SET
				  
				   title = '".escape($title)."', 
				   description = '".escape($description)."', 
				   meta_key = '".escape($meta_k)."',
				   meta_description = '".escape($meta_d)."'
				WHERE
					catalog_id = '$cat_id'
					AND
					lang_id = '$em'
				  ";
				 
		query($sql);
		}
		
		
		
		
		// Връзка с категория
		/*$category_id = $_POST['category_id'];
		
		$sql = "DELETE FROM 
               catalog_to_category
            WHERE
               catalog_id = '$cat_id'
             ";
    	query($sql);
	  
		foreach ($category_id as $key => $value) {
		
			$sql = 'INSERT INTO catalog_to_category
						  ( catalog_id,category_id)
						VALUES
						  ('.$cat_id.', '.intval($value).')
						  ';
			query($sql);
		
		}*/
		
			$upload_path = "../pdf/";
			
			if (is_uploaded_file($_FILES['pdf']['tmp_name'])) {
				$tmp_file = $_FILES['pdf']['tmp_name'];
				$exp = explode('.',$_FILES['pdf']['name']);
				$doc_type = strtolower(end($exp));
				
				$new_name = "product_".$cat_id.".".$doc_type;
				if(copy($tmp_file, $upload_path.$new_name)) {
					
					$sql = "UPDATE catalog
							SET
					doc_description = '$new_name'
							WHERE catalog_id = '$cat_id'";
					query($sql);
					
				} else{
					
					$_SESSION['message'] .= 'Грешка при качване на файл с описание. ';
					
				}
		
		}
		
		$_SESSION['message'] .= 'Артикулът е редактиран успешно!';
       // redirect($redirect);
    }

}
  	
	
	head_admin("Редакция на артикул");
?>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "bg", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,
	
	content_css : "css/editor_style.css"
	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "js/template_list.js",
	//external_link_list_url : "js/link_list.php",
	//media_external_list_url : "js/media_list.js",
	//external_image_list_url : "js/blog_image_list.php"
	
});
</script>
<?php if ($error_message) { ?>

<div class="message red">
  <h3>Грешка!</h3>
  <?=$error_message?>
</div>
<?php }

if ($_SESSION['message']) { ?>

<div class="message green">
  
  <?=$_SESSION['message']?>
</div>
<?php }
			
			$sql = "SELECT 
						catalog_id,
						sef_url,
						doc_description
						
					FROM
						catalog
					WHERE
						catalog_id ='$cat_id'
					
					";
			$result_cat = query($sql);
			$row_catalog = mysql_fetch_object($result_cat);
			$sef = $row_catalog->sef_url;
			$pdf = $row_catalog->doc_description;
			
			
			if ($_POST['is_submitted'])
			{
				$sef = $_POST['seo_url'];
				
			}
			 ?>
<div class="topbuttons"> <a href="<?=$redirect?>">Обратно</a> </div>
<h3>Редактиране на артикул</h3>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="is_submitted" value="1" />
<input type="hidden" name="catalog_id" value="<?=$cat_id?>" />
<input type="hidden" name="image" value="<?=$image?>" />
<input type="hidden" name="redirect" value="<?=$redirect?>" />
<?php 
			
			$sql = 'SELECT lang_id, Name,code
						FROM
						language
						WHERE
						published
					';
			$result = query($sql);
			
			$i=0;
			while ($row_lang = mysql_fetch_object($result)) {
				$em = $row_lang->lang_id;
				
					$sql_d = "SELECT *	
					FROM
						catalog_description
					WHERE
						catalog_id = '$cat_id'
						AND lang_id = '$em'
					
					";
					$result_cat_d = query($sql_d);
					$row_cat_d = mysql_fetch_object($result_cat_d);
					$title = $row_cat_d->title;
					$description = $row_cat_d->description;
					$meta_d = $row_cat_d->meta_description;
					$meta_k = $row_cat_d->meta_key;
					
					
				if ($_POST['is_submitted']) {
				
				eval('$title =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$meta_k =  $_POST[\'meta_key_'.$em.'\'];');
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
				}
				
								  
			?>
<dl class="clearfix">
  <h3>Данни на
    <?=$row_lang->title?>
  </h3>
  <dt>
    <label class="required">Заглавие на
      <?=$row_lang->title?>
    </label>
  </dt>
  <dd>
    <input class="inputbox w500" name="title_<?=$row_lang->lang_id?>" type="text" value="<?=$title?>" >
  </dd>
  <dt>
    <label>Описание на
      <?=$row_lang->title?>
      (</label>
  </dt>
  <dd>
    <textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description_<?=$row_lang->lang_id?>" rows="20"><?=sth($description)?>
</textarea>
  </dd>
  <dl style="float:left;">
    <dt>
      <label >Мета описание </label>
    </dt>
    <dd>
      <textarea class="inputbox w400" name="meta_description_<?=$row_lang->lang_id?>" rows="3" ><?=$meta_d?>
</textarea>
    </dd>
  </dl>
  <dl>
    <dt>
      <label >Ключови думи  (до 110 символа)</label>
    </dt>
    <dd>
      <textarea class="inputbox w400" name="meta_key_<?=$row_lang->lang_id?>" rows="3" maxlength="110"><?=$meta_k?>
</textarea>
    </dd>
  </dl>
</dl>
<?php
				$i++;
			}
			
	  		?>

<dl class="clearfix">
  <dt>
    <label class="required">SEF URL (на латиница, без интервали Пример: this-is-test)</label>
  </dt>
  <dd>
    <input class="inputbox w500" name="seo_url" type="text" value="<?=$sef?>" >
  </dd>
  
  
    <dt>
      <label for="image" class="required">PDF описание - <a href="../pdf/<?=$pdf?>" target="_blank">преглед</a>
       
      </label>
    </dt>
    <dd class="inline clearfix">
      <input class="inputbox" name="pdf" type="file" />
      
    </dd>
 
  
</dl>
<dl class="clearfix">
  <dd class="submit">
    <input type="submit" name="submit" id="submit" value="Запиши">
  </dd>
</dl>
</form>
<dl class="clearfix">
<h3>Снимки</h3>
<form id="im-up" action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
  <input type="hidden" name="is_uploud" value="1" />
  <input type="hidden" name="pro_id" value="<?=$id?>"/>
  <dl class="clearfix">
    Снимките се преоразмеряват автоматично
    <?=IMAGE_WIDTH?>
    x
    <?=IMAGE_HEIGHT?>
    px.
  </dl>
  <dl class="clearfix">
    <dt>
      <label for="image" class="required">Нова снимка
        <?=$row_cat['name']?>
      </label>
    </dt>
    <dd class="inline clearfix">
      <input class="inputbox" name="image" type="file" />
      <input type="submit" name="submit" id="submit" value="Качи">
    </dd>
  </dl>
</form>
<dl>
<?php
            ##########################################################
			//////////////////LOAD IMAGES ////////////////////////////
			
			if(is_dir($dr))
			{
				?>
            <link rel="stylesheet" type="text/css" href="<?=HTML_BASE_ADMIN?>fancybox/jquery.fancybox-1.3.1.css" media="screen" />
            <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 
            <script type="text/javascript" src="<?=HTML_BASE_ADMIN?>fancybox/jquery.fancybox-1.3.1.pack.js"></script> 
            <script type="text/javascript">
                            $(document).ready(function() {
                                $("a[rel=logos]").fancybox({
                                    'transitionIn':'elastic',
                                    'transitionOut':'elastic',
                                    'type':'image',
                                    'titlePosition':'inside'
                                });
                            });
                            </script>
<table id="listing" width="100%" cellpadding="0" cellspacing="0">
  <thead>
    <tr>
      <td>Снимка</td>
      <td>Направи корица</td>
      <td>Премахване</td>
    </tr>
  </thead>
  <tbody>
    <?php		
			
			$sql = "SELECT
					image_id,
					image,
					top
					
				  FROM
					catalog_image
				WHERE 
				 catalog_id = '$id'
				 
				 ORDER BY image_id DESC
				  
					";
		
			$result = query($sql);
		
            while ($row = mysql_fetch_object($result)) {				  
        
						?>
    <tr>
      <td><a href="<?=$dr?><?=$row->image?>"  rel="logos"> <img class="thumb" src="<?=$dr?>th_<?=$row->image?>" height="100"/></a></td>
      <td class="switch"><?php if ($row->top) { ?>
        <a class="turn_on" name="turn_on" title="Това е корица"></a>
        <?php } else { ?>
        <a href="catalog_image_top.php?db=<?=$row->image_id?>&cx=<?=$id?>" class="turn_off" name="turn_off" title="Направи корица"></a>
        <?php } ?></td>
      <td class="icons"><a onClick="if (window.confirm('Сигурен ли си, че искаш да изтриеш ?')) { document.location='catalog_image_del.php?file=<?=$row->image?>&dir=<?=$dr?>&db=<?=$row->image_id?>&cx=<?=$id?>'; return false; }" class="delete" title="Изтрий">Изтрий</a></td>
    </tr>
    <?php
			}
			?>
  </tbody>
</table>
<?php }?>
<script>
			
			
			var p = $('#im-up');
			var position = p.position();
			$('html, body').<?php if($error_message || 
			$_SESSION['message']) echo 'delay(3000).';?>animate({ scrollTop:position.top }, 2000); 
			</script>
<?php
            
			</script>
			<?php 
			unset($_SESSION['message']);
			?>
</dl>

<?php
	foot_admin(); 
?>
